package cj.web.kly.controllers;

import java.io.File;
import java.text.ParseException;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import cj.web.admin.constants.Constants;
import cj.web.admin.utils.DateUtils;
import cj.web.admin.utils.ReadConfigProperties;
import cj.web.admin.utils.ReturnUUID;
import cj.web.kly.constants.NewIsTopStateEnum;
import cj.web.kly.constants.NewReleaseStateEnum;
import cj.web.kly.constants.NewStatusEnum;
import cj.web.kly.constants.NewTypeEnum;
import cj.web.kly.domain.News;
import cj.web.kly.domain.SourceInfor;
import cj.web.kly.domain.SubjectNews;
import cj.web.kly.domain.Subject;
import cj.web.kly.service.SourceInforService;
import cj.web.kly.service.SubjectNewsService;
import cj.web.kly.service.SubjectService;
import cj.web.login.controllers.BaseController;

@Path("/subjectNews")
public class SubjectNewsController extends BaseController{

	private static Logger logger = Logger.getLogger(SubjectNewsController.class.getName());
	
	@Autowired
	private SubjectNewsService newsService;
	
	@Autowired
	private SubjectService subjectService;
	
	@Autowired
	private SourceInforService sourceInforService;
	
	@Get("show")
	public String show(Model model,SubjectNews news) {
		List<Subject> subjectlis = subjectService.queryAll();
		model.add("subjectlis",subjectlis);
		return "/views/kly/subjectNewsList.vm";
	}

	@Post("getList")
	public String queryList(SubjectNews news) throws ParseException {
	
		//当前页  
		news.setStart((news.getPage()-1)*news.getRows());
		news.setLength(news.getRows());
		
		JSONObject jo = new JSONObject();
		
		Map rep = newsService.querySubject(news);
		List<SubjectNews> objs = (List<SubjectNews>) rep.get("subjectNewslis");
		for(SubjectNews obj:objs){
			obj.setReleaseStateName(NewReleaseStateEnum.getName(obj.getReleaseState()));
			obj.setReleaseAt(DateUtils.formatDateStr(obj.getReleaseAt(),DateUtils.DATE_FULL_STR));
			obj.setStickAt(obj.getStickAt()==null?"":obj.getStickAt().toString());
		}
		
		int size = (int) rep.get("size");
		
		jo.put("rows", objs);
		jo.put("total", size);
		return "@"+jo.toString();
	}
	
	@Get("createPage")
	public String createPage(Model model){
		List<Subject> subjectlis = subjectService.queryAll();
		model.add("subjectlis",subjectlis);
		model.add("newIsTopStateEnum",EnumSet.allOf(NewIsTopStateEnum.class));
		List<SourceInfor> sourcelis = sourceInforService.queryAll();
		model.add("sourcelis",sourcelis);
		return "/views/kly/subjectNewsDetail.vm";
	}
	
	@Post("create")
	public String create(Model model,SubjectNews news,HttpServletRequest request,@Param("uploadimage") MultipartFile file){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		try{
			
			news.setDeleteFlag(Constants.deleteFlag.deleteFlag_1);
			news.setCreateUser(returnSessionObj(request).getAccount());
			news.setUpdateUser(returnSessionObj(request).getAccount());
			news.setStatus(NewStatusEnum.TYPE_1.getValue());
			news.setReleaseState(NewReleaseStateEnum.TYPE_0.getValue());
			news.setSubjectColumnsId(Integer.parseInt(news.getTreeIdIn()));
			news.setType(NewTypeEnum.TYPE_1.getValue());
			
			// 判断文件是否为空  
	        if (!file.isEmpty()) {  
	            try {  
	                // 文件保存路径  
	            	String path = ReadConfigProperties.getValue("uploadFilePath");
	            	//判断文件是否存在，不存在创建文件
	            	Map rep = ReturnUUID.getFolder(path);
	            	path = rep.get("allpath").toString();//所在的全路径
	            	//文件名
	                String fileName =  ReturnUUID.getName(file.getOriginalFilename()); 
	                // 转存文件  
	                file.transferTo(new File(path+"/"+fileName));  
	                jo.put("filePath", rep.get("filepath")+"/"+fileName);
	                
	                news.setCarouselImage(rep.get("filepath")+"/"+fileName);//文件路径
	            } catch (Exception e) {  
	                e.printStackTrace();  
	                jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
	            }  
	        } 
			
	        newsService.create(news);
		}catch(Exception e){
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	@Get("edit")
	public String edit(Model model,@Param("id") int id) throws ParseException{
		SubjectNews news = newsService.querySubjectById(id);
		news.setReleaseAt(DateUtils.formatDateStr(news.getReleaseAt(),DateUtils.DATE_FULL_STR));
		List<Subject> subjectlis = subjectService.queryAll();
		model.add("subjectlis",subjectlis);
		model.add("news", news);
		model.add("newIsTopStateEnum",EnumSet.allOf(NewIsTopStateEnum.class));
		List<SourceInfor> sourcelis = sourceInforService.queryAll();
		model.add("sourcelis",sourcelis);
		return "/views/kly/subjectNewsEdit.vm";
	}
	
	@Post("update")
	public String update(Model model,SubjectNews news,HttpServletRequest request,@Param("uploadimage") MultipartFile file){
		JSONObject jo = new JSONObject();
		
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		try {
			
			news.setUpdateUser(returnSessionObj(request).getAccount());
			news.setStatus(NewStatusEnum.TYPE_1.getValue());
			news.setReleaseState(NewReleaseStateEnum.TYPE_0.getValue());
			news.setSubjectColumnsId(Integer.parseInt(news.getTreeIdIn()));
			news.setType(NewTypeEnum.TYPE_1.getValue());
			
			// 判断文件是否为空  
	        if (!file.isEmpty()) {  
	            try {  
	                // 文件保存路径  
	            	String path = ReadConfigProperties.getValue("uploadFilePath");
	            	//判断文件是否存在，不存在创建文件
	            	Map rep = ReturnUUID.getFolder(path);
	            	path = rep.get("allpath").toString();//所在的全路径
	            	//文件名
	                String fileName =  ReturnUUID.getName(file.getOriginalFilename()); 
	                // 转存文件  
	                file.transferTo(new File(path+"/"+fileName));  
	                jo.put("filePath", rep.get("filepath")+"/"+fileName);
	                
	                news.setCarouselImage(rep.get("filepath")+"/"+fileName);//文件路径
	            } catch (Exception e) {  
	                e.printStackTrace();  
	                jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
	            }  
	        } 
			
	        newsService.update(news);
		} catch (Exception e) {
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@" + jo.toString();
	}
	
	@Get("deleteById")
	public String deleteById(Model model,@Param("Ids") String Ids){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		for(String id :Ids.split(",")){
			newsService.deleteById(Integer.parseInt(id));
		}
		
		return "@"+jo.toString();
	}
	
	@Get("newsInfor")
	public String newsInfor(Model model,@Param("id") int id) throws ParseException{
		SubjectNews news = newsService.queryById(id);
		news.setReleaseAt(DateUtils.formatDateStr(news.getReleaseAt(), DateUtils.DATE_SMALL_STR));
		model.add("news", news);
		return "/views/kly/newsInfor.vm";
	}
	
	@Get("stick")//置顶
    public String stick(@Param("Ids") String Ids) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		for(String id :Ids.split(",")){
			newsService.updateByStickTime(Integer.parseInt(id));
		}
		
		return "@"+jo.toString();
	}
	
	@Get("channelStick")//取消置顶
    public String channelStick(@Param("Ids") String Ids) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		for(String id :Ids.split(",")){
			newsService.updateByStickTimeIsNull(Integer.parseInt(id));
		}
		
		return "@"+jo.toString();
	}
	
	@Get("submitNews")//提交新闻
    public String submitNews(@Param("Ids") String Ids) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		for(String id :Ids.split(",")){
			newsService.updateReleaseStateById(Integer.parseInt(id),NewReleaseStateEnum.TYPE_1.getValue());
		}
		
		return "@"+jo.toString();
	}
	
	@Get("channelNews")//撤稿新闻
    public String channelNews(@Param("Ids") String Ids) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		for(String id :Ids.split(",")){
			newsService.updateReleaseStateById(Integer.parseInt(id),NewReleaseStateEnum.TYPE_2.getValue());
		}
		
		return "@"+jo.toString();
	}
	
	/////////////////////////////////
	@Get("showImp")
	public String showImp() {
		return "/views/kly/newsImpList.vm";
	}

	@Post("getImpList")
	public String queryImpList(SubjectNews news) throws ParseException {
	
		//当前页  
		news.setStart((news.getPage()-1)*news.getRows());
		news.setLength(news.getRows());
		
		JSONObject jo = new JSONObject();
		
		Map rep = newsService.query(news);
		List<SubjectNews> objs = (List<SubjectNews>) rep.get("newslis");
		for(SubjectNews obj:objs){
			obj.setReleaseStateName(NewReleaseStateEnum.getName(obj.getReleaseState()));
			obj.setReleaseAt(DateUtils.formatDateStr(obj.getReleaseAt(),DateUtils.DATE_FULL_STR));
			obj.setStickAt(obj.getStickAt()==null?"":obj.getStickAt().toString());
			obj.setTypeName(NewTypeEnum.getName(obj.getType()));
		}
		
		int size = (int) rep.get("size");
		
		jo.put("rows", objs);
		jo.put("total", size);
		return "@"+jo.toString();
	}
	
	@Get("addSelectPage")
	public String addSelectPage(Model model,@Param("Ids") String Ids){
		List<Subject> subjectlis = subjectService.queryAll();
		model.add("subjectlis",subjectlis);
		model.add("Ids",Ids);
		return "/views/kly/subjectNewsImp.vm";
	}
	
	@Post("addSelectFun")
	public String addSelectFun(@Param("Ids") String Ids,@Param("subjectId") int subjectId,
			@Param("treeIdIn") int treeIdIn){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		try {
			newsService.createInsertInto(Ids, subjectId, treeIdIn);
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
}